<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *      [PinTuXiu] (C)2001-2099 ONightjar.com Pintuxiu.com.
 *      This is NOT a freeware, use is subject to license terms
 */

class puzzcode_api{
	
	public function parsesmiles(&$message) {
		$smiles = load_api('setting')->getSmilesWithCode();
		$message = preg_replace($smiles['searcharray'], $smiles['replacearray'], $message, 5);
		return $message;
	}
	
	public function parseurl($url, $text, $scheme) {
		if(!$url && preg_match("/((https?|ftp|gopher|news|telnet|rtsp|mms|callto|bctp|thunder|qqdl|synacast){1}:\/\/|www\.)[^\[\"']+/i", trim($text), $matches)) {
			$url = $matches[0];
			$length = 65;
			if(strlen($url) > $length) {
				$text = substr($url, 0, intval($length * 0.5)).' ... '.substr($url, - intval($length * 0.3));
			}
			return '<a href="'.(substr(strtolower($url), 0, 4) == 'www.' ? 'http://'.$url : $url).'" target="_blank">'.$text.'</a>';
		} else {
			$url = substr($url, 1);
			if(substr(strtolower($url), 0, 4) == 'www.') {
				$url = 'http://'.$url;
			}
			$url = !$scheme ? base_url().$url : $url;
			return '<a href="'.$url.'" target="_blank">'.$text.'</a>';
		}
	}
	
	public function parse_at($message,$type='share'){
		$atlist = $atlist_tmp = array();
		preg_match_all("/@([^\r\n]*?)\s/i", $message.' ', $atlist_tmp);
		$atlist_tmp = array_slice(array_unique($atlist_tmp[1]), 0, 3);
	
		if(!empty($atlist_tmp)) {
			$users = load_api('user')->getUIDSByUnameArray($atlist_tmp);
			foreach($users as $row) {
				$atlist[$row['user_id']] = $row['nickname'];
			}
		}
	
		if($atlist) {
			foreach($atlist as $atuid => $atusername) {
				$atsearch[] = "/@$atusername /i";
				$atreplace[] = "[at=$atuid]@{$atusername}[/at] ";
				$atsearch_str .= "atuser$atuid ";
			}
			$message = preg_replace($atsearch, $atreplace, $message.' ', 1);
		}
		return array('message'=>$message,'atsearch_str'=>$atsearch_str);
	}
	
	public function parse_topic($message){
		$topiclist = $topiclist_tmp = array();
		preg_match_all("/#([^\r\n]*?)#/i", $message.' ', $topiclist_tmp);
		$topiclist_tmp = array_slice(array_unique($topiclist_tmp[1]), 0, 3);
	
		if(!empty($topiclist_tmp)) {
			$topics = load_db('topic')->getTIDSByTopicTitleArray($topiclist_tmp);
			foreach($topics as $row) {
				$topiclist[$row['topic_id']] = $row['topic_title'];
			}
		}
	
		if($topiclist) {
			foreach($topiclist as $tid => $title) {
				$search[] = "/#{$title}#/i";
				$replace[] = "[topic=$tid]#{$title}#[/topic] ";
				$search_str .= 'topic'.pzxencode($title).'t ';
			}
			$message = preg_replace($search, $replace, $message.' ', 1);
		}
		return array('message'=>$message,'search_str'=>$search_str);
	}
	
	public function parse_plain_message($message) {
		$msglower = strtolower($message);
		$message = dhtmlspecialchars($message);
	
		if(strpos($msglower, '[/url]') !== FALSE) {
			$message = preg_replace("/\[url(=((https?|ftp|gopher|news|telnet|rtsp|mms|callto|bctp|thunder|qqdl|synacast){1}:\/\/|www\.|mailto:)?([^\r\n\[\"']+?))?\](.+?)\[\/url\]/ies", "", $message);
		}
	
		$message = str_replace(array('[/at]'), array(''),preg_replace(array("/\[at=(\d+?)\]/i"),array(""), $message));
		$message = str_replace(array('[/topic]'), array(''),preg_replace(array("/\[topic=(\d+?)\]/i"),array(""), $message));
	
	
		$message = str_replace(array(
				'[/color]', '[/backcolor]', '[/size]', '[/font]', '[/align]', '[b]', '[/b]', '[s]', '[/s]', '[hr]', '[/p]',
				'[i=s]', '[i]', '[/i]', '[u]', '[/u]', '[list]', '[list=1]', '[list=a]',
				'[list=A]', "\r\n[*]", '[*]', '[/list]', '[indent]', '[/indent]', '[/float]', '[table]', '[tr]' ,'[td]', '[/table]', '[/tr]' ,'[/td]'
		), array(
				'', '', '', '', '', '', '', '', '', '', '', '', '',
				'', '', '', '', '', '',
				'', '', '', '', '', '', '', '', '', '', '', '', ''
		), preg_replace(array(
				"/\[color=([#\w]+?)\]/i",
				"/\[color=(rgb\([\d\s,]+?\))\]/i",
				"/\[backcolor=([#\w]+?)\]/i",
				"/\[backcolor=(rgb\([\d\s,]+?\))\]/i",
				"/\[size=(\d{1,2}?)\]/i",
				"/\[size=(\d{1,2}(\.\d{1,2}+)?(px|pt)+?)\]/i",
				"/\[font=([^\[\<]+?)\]/i",
				"/\[align=(left|center|right)\]/i",
				"/\[p=(\d{1,2}|null), (\d{1,2}|null), (left|center|right)\]/i",
				"/\[float=left\]/i",
				"/\[float=right\]/i"
	
		), array(
				"",
				"",
				"",
				"",
				"",
				"",
				"",
				"",
				"",
				"",
				""
		), $message));
	
		if(strpos($msglower, '[/quote]') !== FALSE) {
			$message = preg_replace("/\s?\[quote\][\n\r]*(.+?)[\n\r]*\[\/quote\]\s?/is", "", $message);
		}
		if(strpos($msglower, '[/free]') !== FALSE) {
			$message = preg_replace("/\s*\[free\][\n\r]*(.+?)[\n\r]*\[\/free\]\s*/is", "", $message);
		}
	
		if(strpos($msglower, '[/flv]') !== FALSE) {
			$message = preg_replace("/\[flv=([\w,]+)\]\s*([^\[\<\r\n]+?)\s*\[\/flv\]/ies", "", $message);
		}
	
		if(strpos($msglower, '[/audio]') !== FALSE) {
			$message = preg_replace("/\[audio(=1)*\]\s*([^\[\<\r\n]+?)\s*\[\/audio\]/ies","", $message);
		}
		if(strpos($msglower, '[/flash]') !== FALSE) {
			$message = preg_replace("/\[flash(=(\d+),(\d+))?\]\s*([^\[\<\r\n]+?)\s*\[\/flash\]/ies", "", $message);
		}
		if(strpos($msglower, '[/remoteimg]') !== FALSE) {
			$message = preg_replace("/\[remoteimg\]\s*([^\[\<\r\n]+?)\s*\[\/remoteimg\]/ies", "", $message);
		}
		if(strpos($msglower, '[/attachimg]') !== FALSE) {
			$message = preg_replace("/\[attachimg\]\s*([^\[\<\r\n]+?)\s*\[\/attachimg\]/ies", "", $message);
		}
		if(strpos($msglower, '[/attach]') !== FALSE) {
			$message = preg_replace("/\[attach\]\s*([^\[\<\r\n]+?)\s*\[\/attach\]/ies", "", $message);
		}
		if(strpos($msglower, '[/img]') !== FALSE) {
			$message = preg_replace(array(
					"/\[img\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ies",
					"/\[img=(\d{1,4})[x|\,](\d{1,4})\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ies"
			), array(
					"",
					""
			), $message);
		}
	
		unset($msglower);
		$message = trim($message,'\t');
		$message = trim($message,'\n');
		return str_replace(array("\t", '   ', '  ','\n'), array('', '', '',''), $message);
	}
	
	public function parse_message($message,$attaches=null,$needbr=false) {
		if($attaches){
			$GLOBALS['pz_attaches'] = $attaches;
		}
	
		$settingapi = load_api('setting');
		$settings = $settingapi->getSetting('puzzcode');
		$settings = $settings['puzzcode_setting'];
		$parse_attach=$settings['parse_attach'];
		$parse_link=$settings['parse_link'];
		$parse_image=$settings['parse_image'];
	
		$message = preg_replace("/\s?\[code\](.+?)\[\/code\]\s?/ies", "\$this->codedisp('\\1')", $message);
	
		$msglower = strtolower($message);
		$message = dhtmlspecialchars($message);
		$message = $this->parsesmiles($message);
	
		$message = preg_replace("/\s?\[attach\](.+?)\[\/attach\]\s?/ies", "\$this->parseattach('\\1')", $message);
		$message = preg_replace("/\s?\[attachimg\](.+?)\[\/attachimg\]\s?/ies", "\$this->parseattachimg('\\1')", $message);
	
		if(strpos($msglower, '[/url]') !== FALSE) {
			$message = preg_replace("/\[url(=((https?|ftp|gopher|news|telnet|rtsp|mms|callto|bctp|thunder|qqdl|synacast){1}:\/\/|www\.|mailto:)?([^\r\n\[\"']+?))?\](.+?)\[\/url\]/ies", "\$this->parseurl('\\1', '\\5', '\\2')", $message);
		}
		if(strpos($msglower, '[/email]') !== FALSE) {
			$message = preg_replace("/\[email(=([a-z0-9\-_.+]+)@([a-z0-9\-_]+[.][a-z0-9\-_.]+))?\](.+?)\[\/email\]/ies", "\$this->parseemail('\\1', '\\4')", $message);
		}
	
		if(strpos($msglower, '[/flv]') !== FALSE) {
			$message = preg_replace("/\[flv=([\w,]+)\]\s*([^\[\<\r\n]+?)\s*\[\/flv\]/ies", "\$this->parseflv('\\1', '\\2')", $message);
		}
	
		//$userlink = site_url('home/user?uid=\\1');
		//$taglink = site_url_param('pin/index',array('tag'=>'\\1'));
		//$topiclink = site_url('topic/show?topicid=\\1');
		//$message = preg_replace("/#([^#\r\n\]]+?)#/i", "<a href=\"$taglink\" target=\"_blank\">#\\1#</a>", $message, 5);
		$message = str_replace(array('[/at]'), array('</a>'),preg_replace("/\[at=(\d+?)\]/ies","\$this->parseuserlink('\\1')", $message));
		$message = str_replace(array('[/topic]'), array('</a>'),preg_replace("/\[topic=(\d+?)\]/ies","\$this->parsetopiclink('\\1')", $message));
		
		$nest = 0;
		while(strpos($msglower, '[table') !== FALSE && strpos($msglower, '[/table]') !== FALSE){
			$message = preg_replace("/\[table(?:=(\d{1,4}%?)(?:,([\(\)%,#\w ]+))?)?\]\s*(.+?)\s*\[\/table\]/ies", "\$this->parsetable('\\1', '\\2', '\\3')", $message);
			if(++$nest > 4) break;
		}
	
		$message = str_replace(array(
				'[/color]', '[/backcolor]', '[/size]', '[/font]', '[/align]', '[b]', '[/b]', '[s]', '[/s]', '[hr]', '[/p]',
				'[i=s]', '[i]', '[/i]', '[u]', '[/u]', '[list]', '[list=1]', '[list=a]',
				'[list=A]', "\r\n[*]", '[*]', '[/list]', '[indent]', '[/indent]', '[/float]'
		), array(
				'</font>', '</font>', '</font>', '</font>', '</div>', '<strong>', '</strong>', '<strike>', '</strike>', '<hr class="l" />', '</p>', '<i class="pstatus">', '<i>',
				'</i>', '<u>', '</u>', '<ul>', '<ul type="1" class="litype_1">', '<ul type="a" class="litype_2">',
				'<ul type="A" class="litype_3">', '<li>', '<li>', '</ul>', '<blockquote>', '</blockquote>', '</span>'
		), preg_replace(array(
				"/\[color=([#\w]+?)\]/i",
				"/\[color=(rgb\([\d\s,]+?\))\]/i",
				"/\[backcolor=([#\w]+?)\]/i",
				"/\[backcolor=(rgb\([\d\s,]+?\))\]/i",
				"/\[size=(\d{1,2}?)\]/i",
				"/\[size=(\d{1,2}(\.\d{1,2}+)?(px|pt)+?)\]/i",
				"/\[font=([^\[\<]+?)\]/i",
				"/\[align=(left|center|right)\]/i",
				"/\[p=(\d{1,2}|null), (\d{1,2}|null), (left|center|right)\]/i",
				"/\[float=left\]/i",
				"/\[float=right\]/i"
	
		), array(
				"<font color=\"\\1\">",
				"<font style=\"color:\\1\">",
				"<font style=\"background-color:\\1\">",
				"<font style=\"background-color:\\1\">",
				"<font size=\"\\1\">",
				"<font style=\"font-size:\\1\">",
				"<font face=\"\\1\">",
				"<div align=\"\\1\">",
				"<p style=\"line-height:\\1px;text-indent:\\2em;text-align:\\3\">",
				"<span style=\"float:left;margin-right:5px\">",
				"<span style=\"float:right;margin-left:5px\">"
		), $message));
	
		if(strpos($msglower, '[/quote]') !== FALSE) {
			$message = preg_replace("/\s?\[quote\][\n\r]*(.+?)[\n\r]*\[\/quote\]\s?/is", $this->tpl_quote(), $message);
		}
	
		$attrsrc = 'src';
		if(strpos($msglower, '[/img]') !== FALSE) {
			$message = preg_replace(array(
					"/\[img\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ies",
					"/\[img=(\d{1,4})[x|\,](\d{1,4})\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ies"
			), array(
					"\$this->parseimg(0, 0, '\\1', '')",
					"\$this->parseimg('\\1', '\\2', '\\3', '')"
			), $message);
		}
	
		for($i = 0; $i <= $GLOBALS['pz_puzzcode']['pcodecount']; $i++) {
			$message = str_replace("[\tPUZZ_CODE_$i\t]", $GLOBALS['pz_puzzcode']['codehtml'][$i], $message);
		}
	
		unset($msglower);
	
		if($needbr){
			//$message = str_replace(array("\t", '   ', '  '), array('&nbsp; &nbsp; &nbsp; &nbsp; ', '&nbsp; &nbsp;', '&nbsp;&nbsp;'), $message);
			return nl2br($message);
		}else{
			return str_replace(array("\t", '   ', '  '), array('&nbsp; &nbsp; &nbsp; &nbsp; ', '&nbsp; &nbsp;', '&nbsp;&nbsp;'), $message);
		}
	}
	
	function tpl_quote() {
		$return = <<<EOF
<div class="quote"><blockquote>\\1</blockquote></div>
EOF;
		return $return;
	}
	
	public function parsetopiclink($tid){
		return '<a href="'.site_url('topic/show?topicid='.$tid).'">';
	}
	
	public function parseuserlink($uid){
		return '<a href="'.site_url('home/user?uid='.$uid).'"  data-user-id="'.$uid.'" data-user-profile="1">';
	}
	
	public function getAttach($aid){
		if($GLOBALS['pz_attaches']){
			foreach ($GLOBALS['pz_attaches'] as $key=>$attach){
				if($attach['aid']==$aid){
					return $attach;
				}
			}
		}
		return false;
	}
	
	public function getAttachFlv($flv){
		if($GLOBALS['pz_attaches']){
			foreach ($GLOBALS['pz_attaches'] as $key=>$attach){
				if($attach['isimage']==2&&$attach['remote']==$flv){
					return $attach;
				}
			}
		}
		return false;
	}
	
	public function parseflv($params, $url) {
		$params = explode(',', $params);
		$width = intval($params[1]) > 470 ? 470 : intval($params[1]);
		$height = intval($params[2]) > 353 ? 353 : intval($params[2]);
		$attach = $this->getAttachFlv($url);
		$GLOBALS['pz_skipaidlist'][] = $attach['aid'];
		$rs = '<div class="shot-video"><object id="99746" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" height="'.$height.'" width="'.$width.'" type="application/x-shockwave-flash" data="'.$url.'">'.
				'<param name="quality" value="high">'.
				'<param name="bgcolor" value="#000000">'.
				'<param name="allowScriptAccess" value="always">'.
				'<param name="wMode" value="Transparent">'.
				'<param name="swLiveConnect" value="true">'.
				'<param name="allowfullscreen" value="true">'.
				'<param value="'.$url.'" name="movie">'.
				'<embed src="'.$url.'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" wmode="Transparent" width="'.$width.'" height="'.$height.'" style="visibility: visible;" pluginspage="http://get.adobe.com/cn/flashplayer/">'.
				'</object><i class="video_icon hide" orgin_url="'.$attach['source'].'" orgin_src="'.$attach['url'].'"></i></div>';
		return $rs;
	}
	public function parseattach($aid){
		$attach = $this->getAttach($aid);
		$GLOBALS['pz_skipaidlist'][] = $aid;
		if($attach){
			return " <ignore_js_op><span class=\"label label-warning\">".$attach['fileext']."</span> <span class=\"attachinfo\"><a href=\""
					.site_url('accachment/download?aid='.$attach['aid'])."\">{$attach['filename']}</a>(".lang('download_time','tip').": {$attach['downloads']}, ".sizecount($attach['filesize']).")</span></ignore_js_op> ";
		}
	}
	
	public function getAttachUrl($attach,$type='large'){
		if($attach['isimage'])
			return base_url().$attach['attachment'].'_'.$type.'.'.$attach['fileext'];
	}
	
	public function parseattachimg($aid){
		$attach = $this->getAttach($aid);
		$GLOBALS['pz_skipaidlist'][] = $aid;
		if($attach){
			$rs = "<ignore_js_op><div class=\"shot-image\"><img src=\"".$this->getAttachUrl($attach)."\" aid=\"attachimg_".$attach['aid']."\"/>";
			if($attach['description']){
				$rs .= '<div class="shot-pic-desc"><p><i class="sup-ico"></i>'.$img['description'].'<i class="sub-ico"></i></p></div>';
			}
			$rs .= '</div></ignore_js_op>';
			return $rs;
		}
	}
	
	public function parseemail($email, $text) {
		$text = str_replace('\"', '"', $text);
		if(!$email && preg_match("/\s*([a-z0-9\-_.+]+)@([a-z0-9\-_]+[.][a-z0-9\-_.]+)\s*/i", $text, $matches)) {
			$email = trim($matches[0]);
			return '<a href="mailto:'.$email.'">'.$email.'</a>';
		} else {
			return '<a href="mailto:'.substr($email, 1).'">'.$text.'</a>';
		}
	}
	
	public function codedisp($code) {
		$GLOBALS['pz_puzzcode']['pcodecount']++;
		$code = dhtmlspecialchars(str_replace('\\"', '"', $code));
		$code = str_replace("\n", "<li>", $code);
		$GLOBALS['pz_puzzcode']['codehtml'][$GLOBALS['pz_puzzcode']['pcodecount']] = $this->tpl_codedisp($code);
		$GLOBALS['pz_puzzcode']['codecount']++;
		return "[\tPUZZ_CODE_".$GLOBALS['pz_puzzcode']['pcodecount']."\t]";
	}
	public function tpl_codedisp($code) {
		$randomid = 'code_'.random(3);
		$code = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'),  $code);
		$return =
		<<<EOF
<div class="blockcode"><div id="{$randomid}"><ol><li>{$code}</ol></div><em onclick="copycode($('{$randomid}'));">复制代码</em></div>
EOF;
		return $return;
	}
	
	public function parsetable($width, $bgcolor, $message) {
		if(strpos($message, '[/tr]') === FALSE && strpos($message, '[/td]') === FALSE) {
			$rows = explode("\n", $message);
			$s = '<table cellspacing="0" class="t_table" '.
					($width == '' ? NULL : 'style="width:'.$width.'"').
					($bgcolor ? ' bgcolor="'.$bgcolor.'">' : '>');
			foreach($rows as $row) {
				$s .= '<tr><td>'.str_replace(array('\|', '|', '\n'), array('&#124;', '</td><td>', "\n"), $row).'</td></tr>';
			}
			$s .= '</table>';
			return $s;
		} else {
			if(!preg_match("/^\[tr(?:=([\(\)\s%,#\w]+))?\]\s*\[td([=\d,%]+)?\]/", $message) && !preg_match("/^<tr[^>]*?>\s*<td[^>]*?>/", $message)) {
				return str_replace('\\"', '"', preg_replace("/\[tr(?:=([\(\)\s%,#\w]+))?\]|\[td([=\d,%]+)?\]|\[\/td\]|\[\/tr\]/", '', $message));
			}
			if(substr($width, -1) == '%') {
				$width = substr($width, 0, -1) <= 98 ? intval($width).'%' : '98%';
			} else {
				$width = intval($width);
				$width = $width ? ($width <= 560 ? $width.'px' : '98%') : '';
			}
			return '<table cellspacing="0" class="t_table" '.
					($width == '' ? NULL : 'style="width:'.$width.'"').
					($bgcolor ? ' bgcolor="'.$bgcolor.'">' : '>').
					str_replace('\\"', '"', preg_replace(array(
							"/\[tr(?:=([\(\)\s%,#\w]+))?\]\s*\[td(?:=(\d{1,4}%?))?\]/ie",
							"/\[\/td\]\s*\[td(?:=(\d{1,4}%?))?\]/ie",
							"/\[tr(?:=([\(\)\s%,#\w]+))?\]\s*\[td(?:=(\d{1,2}),(\d{1,2})(?:,(\d{1,4}%?))?)?\]/ie",
							"/\[\/td\]\s*\[td(?:=(\d{1,2}),(\d{1,2})(?:,(\d{1,4}%?))?)?\]/ie",
							"/\[\/td\]\s*\[\/tr\]\s*/i"
					), array(
							"\$this->parsetrtd('\\1', '0', '0', '\\2')",
							"\$this->parsetrtd('td', '0', '0', '\\1')",
							"\$this->parsetrtd('\\1', '\\2', '\\3', '\\4')",
							"\$this->parsetrtd('td', '\\1', '\\2', '\\3')",
							'</td></tr>'
					), $message)
					).'</table>';
		}
	}
	
	public function parsetrtd($bgcolor, $colspan, $rowspan, $width) {
		return ($bgcolor == 'td' ? '</td>' : '<tr'.($bgcolor ? ' style="background-color:'.$bgcolor.'"' : '').'>').'<td'.($colspan > 1 ? ' colspan="'.$colspan.'"' : '').($rowspan > 1 ? ' rowspan="'.$rowspan.'"' : '').($width ? ' width="'.$width.'"' : '').'>';
	}
	
	
	public function parseimg($width, $height, $src, $extra = '') {
		if(strstr($src, 'file:') || substr($src, 1, 1) == ':') {
			return $src;
		}
		if($width > 400) {
			$height = intval(400 * $height / $width);
			$width = 400;
	
			$extra = 'style="cursor:pointer"';
	
		}
		$attrsrc = 'src';
		$rimg_id = random(5);
		return $this->bbcodeurl($src, '<img '.($width > 0 ? ' width="'.$width.'"' : '').($height > 0 ? ' height="'.$height.'"' : '').' '.$attrsrc.'="'.$src.'" '.($extra ? $extra.' ' : '').'border="0" alt="" />');
	}
	
	
	public function bbcodeurl($url, $tags) {
		if(!preg_match("/<.+?>/s", $url)) {
			if(!in_array(strtolower(substr($url, 0, 6)), array('http:/', 'https:', 'ftp://', 'rtsp:/', 'mms://')) && !preg_match('/^static\//', $url) && !preg_match('/^data\//', $url)) {
				$url = 'http://'.$url;
			}
			return str_replace(array('submit', site_url('user/login')), array('', ''), str_replace('{url}', addslashes($url), $tags));
		} else {
			return '&nbsp;'.$url;
		}
	}
	
}